package cn.bxshey.resourceSharing.controller;

import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * @作者：不想说话而已
 * @Date：2023/12/21 20:00
 */

@RestController
public class LoadController {
    @GetMapping("/download")
    public ResponseEntity<FileSystemResource> downloadFile(String file) throws IOException, IOException {
        //将文件名作为文件内容

        // 创建临时文件并写入文章内容
        File tempFile = File.createTempFile(file, ".txt");
        Files.write(tempFile.toPath(), file.getBytes());

        // 设置响应头，告诉浏览器下载文件
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        String encode = URLEncoder.encode(file + ".txt", StandardCharsets.UTF_8.name());
        headers.setContentDispositionFormData("attachment", encode);

        // 将临时文件作为响应体返回给客户端进行下载
        return ResponseEntity
                .ok() //标识状态码为ok
                .headers(headers) //设置请求头
                .body(new FileSystemResource(tempFile)); //将文件内容 作为响应体
    }
}
